package com.shilei.iterator.v3;

/**
 * @description: 构建一个容器 ，可以添加对象  链表
 * @author: 81271
 * @date: 2020-04-19 19:52
 */

class LinkedList_<E> implements Collection_<E>{
    private Node<E> head = null;
    private Node<E> tail = null;

    private int size = 0;

    @Override
    public void add(E e) {
        Node<E> node = new Node<>(e);
        node.next = null;

        if (head == null) {
            head = node;
            tail = node;
        }
        tail.next = node;
        tail = node;

        size ++;
    }

    private class Node<E> {
        private E e;
        Node next;

        public Node(E e) {
            this.e = e;
        }

        public E getValue() {
            return e;
        }
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public Iterator_<E> iterator() {
        return new LinkedListIterator();
    }

    private class LinkedListIterator implements Iterator_<E>{
        private Node<E> curr;
        private Node<E> next = head;
        private int nextIndex;


        @Override
        public boolean hasNext() {
            return nextIndex < size;

        }

        @Override
        public E next() {
            curr = next;
            next = next.next;
            nextIndex++;
            return curr.getValue();
        }
    }
}

